var treeObj;
//页面控件初始化
$(document).ready(function() {

    // $( "#progressbar" ).progressbar({
    //     value:0
    // });
    getMenus();
    $("#uploadIcoBtn").bind("click",icoUpload);
    $("#cleanIcoBtn").bind("click",function(){
        $("#mtIcoFile").val("");
        $( "#progressbar" ).progressbar("option", "value",0);
        $("#progressValue").text("");
        $("#imgIco").attr("src","");
        $("#icoUrl").val("");
    });
    $("#mtIcoFile").bind("click",function(){
        $( "#progressbar" ).progressbar("option", "value",0);
        $("#progressValue").text("");
    });

    //$("#imgIco").bind("click",listIcos);

    // initPanel("menuIcosPanel",basePath+"gzmli/menu/listIcos.wdf",basePath,"imgIco",function(img,obj){
    //     $("#imgIco").attr("src",basePath+img.icoUrl);
    //     $("#icoUrl").val(img.icoUrl.substring(img.icoUrl.indexOf("/")+1));
    // });
});
//返回菜单信息
function getMenus() {

    treeObj=$.fn.zTree.init($("#sysmenus"), setting,[{id:1,pId:"wdfMenu",name:"系统菜单",isParent:true}]);
    var nodes = treeObj.getNodes();
    if (nodes.length>0) {
        treeObj.reAsyncChildNodes(nodes[0], "refresh");
    }
}

function ajaxDataFilter(treeId, parentNode, data) {
    var childNodes = data.data;
    if (childNodes) {
        for(var i =0; i < childNodes.length; i++) {

            //childNodes[i].url="<%=path%>/"+childNodes[i].url;
            if(!childNodes[i].icon||childNodes[i].icon==''){
                childNodes[i].icon=undefined;
                childNodes[i].icoUrl="";
            }else{
                var zoomPath=childNodes[i].icon;
                childNodes[i].icon=basePath+"resource/ico/menuico/"+zoomPath;
                childNodes[i].icoUrl=zoomPath;
            }
            if($("#testMenu").text()=="编辑状态"&&childNodes[i].url&&childNodes[i].url!=''){
                if(childNodes[i].url.lastIndexOf("http")<0){
                    childNodes[i].url=basePath+childNodes[i].url;
                }
            }
            childNodes[i].isParent=childNodes[i].isParent==0?false:true;

        }
    }
    return childNodes;
};
//选中节点
var selectedNode = null;
//当前节点
var currentNodes = null;
//当前序列
var oldorder;
//树节点对象
var treenode;
//zTree配置信息详细参数见帮助文档
var setting = {
    view : {
        addHoverDom : addHoverDom,
        removeHoverDom : removeHoverDom,
        selectedMulti : false
    },
    async : {
        autoParam : ["id=pId"],
        enable: true,
        type : "post",
        dataFilter:ajaxDataFilter,
        url : basePath+"/menu/listByCondition"
    },
    edit : {
        enable : true,
        showRemoveBtn :true,//禁用删除
        showRenameBtn : false
    },
    data : {
        simpleData : {
            enable : true
        }
    },
    callback : {
        beforeDrag : beforeDrag,
        beforeEditName : beforeEditName,
        beforeRemove : beforeRemove,
        beforeRename : beforeRename,
        //onRemove : onRemove,
        onRename : onRename,
        onClick : zTreeOnClick
    }
};
//单击菜单节点事件
function zTreeOnClick(event, treeId, treeNode) {
    selectedNode = treeNode;
    if($("#testMenu").text()=="编辑状态")
        return;
    if(treeNode.id==1)
        return;
    $("#mid").val(treeNode.id);
    $("#mpid").val(treeNode.pId);
    //$("#mno").val(treeNode.menuNo);
    $("#murl").val(treeNode.url);
    $("#mname").val(treeNode.name);
    $("#mdescription").val(treeNode.description);
    if(treeNode.icon){
        $("#imgIco").attr("src",treeNode.icon);
    }
    else{
        $("#imgIco").attr("src","");
    }
    $("#icoUrl").val(treeNode.icoUrl);
    $("#morderno").val(treeNode.orderNo);

    oldorder=treeNode.orderNo;
    treenode=treeNode;
}


var log, className = "dark";
function beforeDrag(treeId, treeNodes) {
    return false;
}
function beforeEditName(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; "
        + treeNode.name);
    var zTree = $.fn.zTree.getZTreeObj("sysmenus");
    zTree.selectNode(treeNode);
    return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？");
}
function beforeRemove(treeId, treeNode) {
    className = (className == "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; "
        + treeNode.name);
    return removeMenu(treeNode);

}
function beforeRename(treeId, treeNode, newName) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; "
        + treeNode.name);
    if (newName.length == 0) {
        alert("节点名称不能为空.");
        var zTree = $.fn.zTree.getZTreeObj("sysmenus");
        setTimeout(function() {
            zTree.editName(treeNode)
        }, 10);
        return false;
    }
    return true;
}
function onRename(e, treeId, treeNode) {
    showLog("[ " + getTime() + " onRename ]&nbsp;&nbsp;&nbsp;&nbsp; "
        + treeNode.name);
}
function showLog(str) {
    if (!log)
        log = $("#log");
    log.append("<li class='"+className+"'>" + str + "</li>");
    if (log.children("li").length > 8) {
        log.get(0).removeChild(log.children("li")[0]);
    }
}
function getTime() {
    var now = new Date(), h = now.getHours(), m = now.getMinutes(), s = now
        .getSeconds(), ms = now.getMilliseconds();
    return (h + ":" + m + ":" + s + " " + ms);
}

//节点数记录
var newCount = 1;


//添加新节点回调函数,同时用于添加节点添加图标
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.id).length > 0)
        return;
    //添加菜单添加btn
    var addStr = "<button type='button' style='vertical-align:middle' class='add' id='addBtn_"
        + treeNode.id
        + "' title='add node' onfocus='this.blur();'></button>";
    sObj.append(addStr);
    var btn = $("#addBtn_" + treeNode.id);
    if (btn)
        btn.bind("click", function() {
            var zTree = $.fn.zTree.getZTreeObj("sysmenus");

            //每添加一个新节点都要先把节点信息发送给服务端并确保服务端创建成功
            addMenu(getTime(), zTree, treeNode);

            return false;
        });
}

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.id).unbind().remove();
}
function selectAll() {
    var zTree = $.fn.zTree.getZTreeObj("sysmenus");
    zTree.setting.edit.editNameSelectAll = $("#selectAll").attr("checked");
}

//添加菜单
function addMenu(name, tree, treeNode) {
    // var uuid=new UUID();
    // uuid = new String(uuid).replace(/\-+/g,"");
    currentNodes = $.fn.zTree.getZTreeObj("sysmenus").getNodes();
    var subNodes=$.fn.zTree.getZTreeObj("sysmenus").getNodesByParam("pId",treeNode.id,treeNode);
    var orderNo=0;
    for(var i=0;i<subNodes.length;i++){
        if(orderNo=0){
            orderNo=subNodes[i].orderNo;
            continue;
        }
        else if(subNodes[i].orderNo>orderNo)
        {
            orderNo=subNodes[i].orderNo;
        }
    }
    orderNo++;
    //JSON.stringify();
    $.post(basePath+"/menu/save",{
        // "id":uuid,
        "parent.id":treeNode.id,
        "name":name,
        //"menu.ico" : "../../images/menuimg/Modify.png",
        "url" : "",
        "target" : "iframeContent",
        "orderNo": orderNo,
        "isParent":0
    }, function(data) {
        if (data.status) {
            //添加节点
            if(data.status==1)
            {
                tree.addNodes(treeNode, {
                    id :data.data.id,
                    pId : treeNode.id,
                    name : name,
                    //icon : "../../images/menuimg/Modify.png",
                    url : "",
                    target : "iframeContent",
                    isParent : 0
                });
            }
            else{
                alert(data.msg);
            }
        } else {
            alert("添加失败！");

        }
    });
}

//更新节点信息
function updateMenu() {
    //executeVal(valparam)
    if($("#testMenu").text()=="编辑状态")
        return;
    if(treenode.id!=$("#mid").val())
        return;
    if (executeVal(valparam)) {
        currentNodes = $.fn.zTree.getZTreeObj("sysmenus").getNodes();
        $.wdfProgress.progress("请稍等...",$("body"));
        var parent=false;
        $.ajax({
            url:basePath+"/menu/update",
            type:"POST",
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            data:{
                "id" : $("#mid").val(),
                "parent.id" : $("#mpid").val(),
                "pId": $("#mpid").val(),
                //"isParent":treenode.id==$("#mid").val()?treenode.isParent:false,
                "name" : $("#mname").val(),
                "icon" : $("#icoUrl").val().substr($("#icoUrl").val().lastIndexOf("/")+1),
                "url" : $("#murl").val(),
                "description" : $("#mdescription").val(),
                "orderNo":$("#morderno").val(),
                "isParent":treenode.isParent?1:0

            },
            success : function(data) {
                if (data.status == 1) {
                    //刷新树菜单
                    //getMenus();
                    if(treenode&&treenode.id==$("#mid").val())
                    {
                        treenode.name=$("#mname").val();
                        treenode.url=$("#murl").val();
                        treenode.description=$("#mdescription").val();
                        treenode.orderNo=$("#morderno").val();
                        if($("#icoUrl").val()!=""){
                            treenode.icon=basePath+$("#icoUrl").val();
                        }
                        else{
                            treenode.icon=undefined;
                        }
                        //$.fn.zTree.getZTreeObj("sysmenus").updateNode(treenode);
                        treeObj.reAsyncChildNodes(treenode.getParentNode(), "refresh");
                        //orderNode(treenode,$("#morderno").val(),oldorder);
                        //oldorder=$("#morderno").val();
                        $.wdfProgress.showMsg(data.msg,$("body"));
                        $.wdfProgress.progRemove($("body"), function() {
                        },1666)
                        //$.fn.zTree.getZTreeObj("sysmenus").refresh();

                    }
                } else {
                    alert("更新失败！");

                }
            }
        });
    }

    else
    {
        setTimeout(removeAllMsg,3000);

    }
}
//测试菜单测试链接和编辑状态切换
function testMenu(obj) {
    if ($(obj).text() == "测试链接") {
        setting.edit.enable = false;
        getMenus();
        $(obj).text("编辑状态");

    } else {
        setting.edit.enable = true;
        getMenus();
        $(obj).text("测试链接");
    }
}

//移出菜单节点
function removeMenu(treeNode) {
    if(!confirm("确认删除节点 -- " + treeNode.name + " 吗？")){
        return false;
    }
    //执行更新操作时先记录当前节点用作计算信息
    //currentNodes = $.fn.zTree.getZTreeObj("sysmenus").getNodes();
    var parentNode=treeNode.getParentNode();
    //判断移出该节点后节点父节点是否还是是父节点
    var isParent=0;
    if(parentNode&&parentNode.children){
        isParent=parentNode.children.length-1>0?1:0;
    }
    //如果是父节点或根节点
    if (treeNode.isParent || treeNode.id == "0") {

        alert("该节点非叶节点或是系统根节点故无法移出！");
        return false;

    }
    $.post(basePath+"/menu/delete", {
        "id" : treeNode.id,
        "pId":treeNode.pId,
        "isParent":isParent
    }, function(data) {
        if(data.status)
        {
            if (data.status == 1) {
                $.fn.zTree.getZTreeObj("sysmenus").removeNode(treenode);
                alert(data.msg);

            } else {
                alert(data.msg);
            }
        }
        else
        {
            alert("数据请求失败！");
        }
    });

}
//记录节点当前展开状态
function recordOpen(currentNodes, nodes) {

    if (currentNodes != null) {

        for ( var i = 0; i < currentNodes.length; i++) {
            for ( var i1 = 0; i1 < nodes.length; i1++) {

                if (currentNodes[i].id == nodes[i1].id) {
                    nodes[i1].open = currentNodes[i].open
                    //alert(currentNodes[i].open);

                    if (currentNodes[i].isParent) {
                        nodes = recordOpen(currentNodes[i].children, nodes);

                    }
                }

            }

        }

    }
    return nodes;
}


//菜单属性验证参数
var valparam = [ {
    inputname : "mname",
    isnull : true,
    isnullmsg : "菜单名称不能为空!"

}
    ,{
        inputname : "morderno",
        isnull : true,
        isnullmsg : "请输入序列!",
        integer: true,
        integermsg:"序列只能是整数!"

    }
];

function updateMenus()
{
    orderno=undefined;
    $("#mid").val("");
    $("#mpid").val("");
    $("#mname").val("");
    //"menu.ico" : $("#micon").attr("src"),
    $("#murl").val("");
    $("#mdescription").val("");
    $("#morderno").val("");
    $("#mno").val("");
    $("#progressValue").text("");
    $("#imgIco").attr("src","");
    $("#icoUrl").val("");
    $("#mtIcoFile").val("");
    $( "#progressbar" ).progressbar("option", "value",0);
    getMenus();

}




//图标上传
function icoUpload(){
    /* !executeVal([{
     inputname : "mtIcoFile",
     postfix : true
     }]) */
    if(!executeVal([{
        inputname : "mtIcoFile",
        postfix : true
    }]))
    {
        setTimeout(removeAllMsg,3000);
        return;
    }

    statusName=new String(new UUID()).replace(/-+/g,"");
    $("#uploadIcoForm").attr("action",$("#uploadIcoForm").attr("action").replace(/(\&statusName\=)+\w{32}/,"")+"&statusName="+statusName);
    $("#uploadIcoForm").submit();
    $( "#progressbar" ).progressbar("option", "value",0);
    setTimeout(listenProgress,500);

}
//图标上传进度监听
function listenProgress(){
    $.ajax({
        url:basePath+"/pages/wdfUpload.wdf?statusName="+statusName,
        //processData: false,
        //data: xmlDocument,
        dataType:"json",
        type: "GET",
        contentType:"application/x-www-form-urlencoded; charset=GB2312",
        beforeSend:null,
        success:function(data){

            if(data.reqstate&&data.reqstate.state==1)
            {
                $("#progressValue").text(data.percent+"%");
                $( "#progressbar" ).progressbar("option", "value",parseInt(data.percent));
                //上传未完
                if($( "#progressbar" ).progressbar("option","value")<100){
                    setTimeout(listenProgress,100);
                }
                //上传完毕
                else{

                    if(data.icoPath!='null'){
                        var zoomPath=data.icoPath.substring(0,data.icoPath.lastIndexOf("."))+"_zoom16x16"+data.icoPath.substring(data.icoPath.lastIndexOf("."));
                        $("#imgIco").attr("src",basePath+zoomPath);
                        $("#icoUrl").val(zoomPath);
                    }
                    else{
                        setTimeout(listenProgress,100);
                    }
                }
            }
            else if(data.reqstate&&data.reqstate.state==0){
                $("#progressValue").text(data.reqstate.msg);
            }

        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            $("#progressValue").text("服务器响应异常！");

        }
    });}
